<!--Echarts组件-->
<template>
  <div ref="main" class="main" :style="{ width: width, height: height }" />
</template>

<script lang="ts" setup>
import {
  ref,
  defineProps,
  watch,
  onMounted,
  onBeforeUnmount,
  withDefaults,
} from 'vue'
import * as echarts from 'echarts'
import { ECBasicOption, EChartsType } from 'echarts/types/dist/shared'
import { EventParams } from '@/echart.enum'
interface EchartsProps {
  options: ECBasicOption | null
  width: string
  height: string
  handlerClick: (params: EventParams) => void | null
  theme: string
}
let instance: EChartsType = null as unknown as EChartsType
const props = withDefaults(defineProps<EchartsProps>(), {
  width: '100%',
  height: '100%',
  theme: '',
})
const main = ref(null)
// 初始化图表
const initEcharts = () => {
  if (props.options == null) return
  instance = echarts.init(
    main.value as unknown as HTMLElement,
    props.theme,
  ) as unknown as EChartsType
  instance.setOption(props.options as ECBasicOption)
  instance.on('click', handlerClick)
  window.onresize = handlerSize
  // console.log(instance)
}
function handlerSize() {
  instance.resize()
}
function handlerClick(params: EventParams | any): void {
  if (props.handlerClick != null) {
    props.handlerClick(params)
  }
}
onMounted(() => {
  initEcharts()
})
onBeforeUnmount(() => {
  if (instance.id) {
    instance.dispose()
    window.removeEventListener('onresize', handlerSize)
  }
})
// 监听数据变化
watch(props, () => {
  if (instance.id) {
    instance.setOption(props.options as ECBasicOption)
  }
})
</script>

<style scoped lang="scss">
.main {
  width: 100%;
  height: 100%;
}
</style>
